<?php

namespace app\admin\controller;

use think\Db;
use think\Controller;
use think\Request;
use think\Session;

class Main extends Controller
{
    /**
     * 后台主页
     * @return \think\response\View
     */
    public function index()
    {
        $this->redirect('/admin/main/login.html');
    }


    public function login()
    {
        if(Session::has('admin_user')){
            //跳转到 首页
            $this->error('您已登录, 不要搞事情!(╬◣д◢)', '/admin/index/index');
        }
        return view('index/login');
    }

    public function logindo(Request $request)
    {
        $username = input('post.username');
        $password = input('post.password');

        $data = Db::name('user')->where(['username' => $username])->find();

        // 验证用户名是否存在
        if (!$data) {
            $this->error('用户名不存在！');
            exit;
        }
        //验证密码
        if ($data['userpass'] != md5($password)) {
            $this->error('密码不正确');
            exit;
        }

        // 存SESSION
        Session::set('admin_user',$data);
//        $_SESSION['admin_user'] = $data;

        //根据用户id获取对应的节点信息
        //$sql = "select n.mname,n.aname from lamp_user u join lamp_user_role ur on u.id=ur.uid join lamp_role_node rn on ur.rid=rn.rid join lamp_node n on rn.nid=n.id where u.id={$users['id']}";
        //$list = M()->query($sql);

        $row = Db::name('user_role')->where(['uid' => $data['id']])->select();
        foreach ($row as $v) {
            $role[] = $v['rid'];
        }
        foreach ($role as $v) {
            $col[] = Db::name('role_node')->where(['rid' => $v])->select();
        }
        foreach ($col as $x) {
            foreach ($x as $k => $v) {
                $node[] = $v['nid'];
            }
        }
        $node = array_unique($node);
//        var_dump($node);die;
        foreach ($node as $k) {
            $one[] = Db::name('node')->field(['mname', 'aname'])->where(['id' => $k])->select();
        }
        foreach ($one as $x) {
            foreach ($x as $v) {
                $res[] = $v;
            }
        }
        foreach ($res as $k => $v) {
            $res[$k]['mname'] = ucfirst($v['mname']);
        }

        $nodelist = array();
        $nodelist['Index'] = array('index', 'logout');
        $nodelist['Main'] = array('index');
        foreach ($res as $k) {
            $nodelist[$k['mname']][] = $k['aname'];
        }

//        var_dump($nodelist);die;

        //将权限信息放置到session中
        Session::set('admin_user.nodelist', $nodelist);
//        $_SESSION['admin_user']['nodelist'] = $nodelist;

        return $this->success('登录成功!', 'admin/index/index');
    }

}
